package com.twelve.all.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.widget.Toast;

import com.twelve.all.R;
import com.twelve.all.utils.CommonProgressDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * author: 张龙臣
 * <p>
 * 请求服务器版本后与本地版本进行比较，如果有新版本
 * 一、判断存储权限
 * 有存储权限  --> 下载安装
 * 无存储权限  --> 权限请求 --> 请求成功 --> 下载安装
 * 请求失败 -->
 * 提示必须给权限才能安装新版本（强制更新给出相应的提示），
 * 再次请求 --> 请求成功 --> 下载安装
 * 请求失败 --> 判断此次跟新是否为强制更新 --> 是强制更新 --> 退出应用
 * 非强制跟新 --> 放弃更新正常使用
 * <p>
 * 二、下载，判断是否为8.0或以上版本
 * 8.0以下版本     --> 直接想下载
 * 8.0或以上版本   --> 判断安装外来应用权限 --> 有权限 --> 下载
 * 无权限 --> 对话框去权限界面（强制更新给出相应的提示）
 * --> 不去：
 * 是强制更新--> 退出应用
 * 非强制跟新--> 放弃更新正常使用
 * -->  打开权限界面，回到应用判断：
 * 已打开安装外部apk权限 --> 下载
 * 未打开：
 * 是强制更新--> 退出应用
 * 非强制跟新--> 放弃更新正常使用
 * <p>
 * 三、安装
 * 7.0以上需要用到FileProvider
 * <p>
 * ( 待优化：读取已下载apk)
 */
public class UpdateVersionActivity extends PermissionActivity {

    private static final String TAG = "UpdateVersionActivity";
    private CommonProgressDialog pBar;
    // 下载存储的文件名
    private static final String DOWNLOAD_NAME = "dispatch";
    public static final int INSTALL_PACKAGES_REQUESTCODE = 120;

    protected String content;
    protected String url;
    protected boolean wgt;
    private DownloadTask downloadTask;

    protected String mServerVersion = null;

    @Override
    protected void onGranted(int requestCode) {
        switch (requestCode) {
            case STORAGE_CODE:
                LogUtil.w("-----------STORAGE_CODE-------------------");
                if (mWhich == 0)
                    LogUtil.w("-----------if-------------------");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !getPackageManager().canRequestPackageInstalls()) {
                    showOpenInstallPackage(wgt, UpdateVersionActivity.this);
                } else {
                    LogUtil.w("-----------else-------------------");
                    ShowUpdateDialog(wgt, content, url);
                }
                break;
        }
    }

    @Override
    protected void onProhibited(int requestCode) {
        switch (requestCode) {
            case STORAGE_CODE:
//                StringBuilder sb = new StringBuilder().append(getString(R.string.storage));
//                if (wgt) {
//                    sb.append("\n本次跟新为强制更新，若不更新APP将无法使用");
//                }
//                EasyPermissions.requestPermissions(this, sb.toString(), Permissions.STORAGE_CODE, Permissions.STORAGE);
                exitApp();
                break;
        }
    }

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
////        getServerVersion();
//    }
//    private void getServerVersion() {
//        //请求服务器版本
//        NetManager.getInstance().doSubscribe(new NetManager.Model<ServerVersionInfo>(new CallBack<ServerVersionInfo>() {
//            @Override
//            public void onCompleted(ServerVersionInfo serverVersionInfo) {
//                content = "\n" + "已有新的版本了，请更新后再使用\n";
//                url = "http://np.bv-cloud.com:7070/app/ToolsManagement.apk";//安装包下载地址
//                wgt = serverVersionInfo.wgt;
//                String mServerVersion = serverVersionInfo.version;
//                String localVersionName = PackageUtil.getLocalVersionName(UpdateVersionActivity.this);
//                boolean b = mServerVersion.compareTo(localVersionName) > 0;
//                if (b) {
//                    strorageTask();
//                }
//            }
//
//            @Override
//            public void onError() {
//
//            }
//        }) {
//            @Override
//            protected Observable<ResponseInfo<ServerVersionInfo>> getObservable() {
//                return NetManager.getResponseInfoAPI().getServerVersion("android");
//            }
//        });
//    }

//    protected void installNewApk() {
//        strorageTask();
//    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 升级系统
     *
     * @param wgt
     * @param content
     * @param url
     */
    private void ShowUpdateDialog(final boolean wgt, String content, final String url) {
        new android.app.AlertDialog.Builder(this)
                .setTitle("版本更新")
                .setMessage(content)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        pBar = new CommonProgressDialog(UpdateVersionActivity.this);
                        pBar.setCanceledOnTouchOutside(false);
                        pBar.setTitle("正在下载");
                        pBar.setCustomTitle(LayoutInflater.from(UpdateVersionActivity.this).inflate(R.layout.title_dialog, null));
                        pBar.setMessage("正在下载");
                        pBar.setIndeterminate(true);
                        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pBar.setCancelable(false);
                        // downFile(URLData.DOWNLOAD_URL);
                        downloadTask = new DownloadTask(UpdateVersionActivity.this);
                        downloadTask.execute(url);
                        LogUtil.w(url);
                        pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                downloadTask.cancel(true);
                            }
                        });
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (wgt) {
                            exitApp();
                        }
                    }
                })
                .setCancelable(false)
                .show();
    }

    /**
     * 下载应用
     */
    private class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            File file = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error
                // report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return " "
                            + connection.getResponseCode() + " "
                            + connection.getResponseMessage();
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    file = new File(Environment.getExternalStorageDirectory(), DOWNLOAD_NAME);
                    if (!file.exists()) {
                        // 判断父文件夹是否存在
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                    }

                } else {
                    Toast.makeText(UpdateVersionActivity.this, "sd卡未挂载", Toast.LENGTH_LONG).show();
                }
                input = connection.getInputStream();
                output = new FileOutputStream(file);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);

                }
            } catch (Exception e) {
                System.out.println(e.toString());
                return e.toString();

            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (pm != null) {
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
                mWakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
            }
            pBar.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pBar.setIndeterminate(false);
            pBar.setMax(100);
            pBar.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            pBar.dismiss();
            if (result != null) {
//                Toast.makeText(context, "您未打开SD卡权限" + result, Toast.LENGTH_LONG).show();
//                Toast.makeText(context, "下载失败" + result, Toast.LENGTH_LONG).show();
                ToastUtil.showCenterToast("下载失败" + result);
                exitApp();
            } else {
                boolean installAllowed;
                File file = new File(Environment.getExternalStorageDirectory(), DOWNLOAD_NAME);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    installAllowed = context.getPackageManager().canRequestPackageInstalls();
                    if (installAllowed) {
                        installApk(file);
                    } else {
//                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.getPackageName()));
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        UpdateVersionActivity.this.startActivityForResult(intent, INSTALL_PACKAGES_REQUESTCODE);
                        showOpenInstallPackage(wgt, UpdateVersionActivity.this);
                    }
                } else {
                    installApk(file);
                }
            }
        }
    }

    //安装apk，兼容7.0
    protected void installApk(File file) {
        if (!file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    //-----   放下面去了就报错
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //参数1 上下文, 参数2 Provider主机地址和清单文件中保持一致   参数3 共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, "com.hangwei.paperless.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void showOpenInstallPackage(final boolean wgt, final Activity activity) {
        StringBuilder sb = new StringBuilder();
        sb.append("需要安装外部apk权限");
        if (wgt)
            sb.append(" \n本次更新为强制更新，更新后才能使用！");
        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("权限请求");
        builder.setMessage(sb.toString());
        builder.setCancelable(false);
        final AlertDialog dialog = builder.create();
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "开启权限", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + activity.getPackageName()));
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);不能开新的任务栈，不然收不到回调
                activity.startActivityForResult(intent, INSTALL_PACKAGES_REQUESTCODE);
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, wgt ? "退出应用" : "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                if (wgt)
                    exitApp();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case INSTALL_PACKAGES_REQUESTCODE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && getPackageManager().canRequestPackageInstalls()) {
                    ShowUpdateDialog(wgt, content, url);
                } else {
//                    if (wgt)
//                        exitApp();
                    LogUtil.d("未打开安装应用权限，无法安装");
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        //处理用户在安装界面返回，不安装的情况
//        if (mServerVersion != null) {
//            String localVersionName = PackageUtil.getLocalVersionName(this);
//            boolean b = mServerVersion.compareTo(localVersionName) > 0;
//            File file = new File(Environment.getExternalStorageDirectory(), DOWNLOAD_NAME);
//            if (b && wgt) {  //需要跟新
//                if (file.exists()) {// 已经下载了，执行安装
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //判断安卓版本是否是8.0以上的
//                        //判断是否有安装权限
//                        boolean installAllowed = getPackageManager().canRequestPackageInstalls();
//                        if (installAllowed) {
//                            installApk(file);
//                        } else {
//                            //无安装权限发起请求
//                            showOpenInstallPackage(wgt, UpdateVersionActivity.this);
//                        }
//                    } else {//8.0以下直接安装
//                        installApk(file);
//                    }
//                } else { //没有下载，执行下载
//                    mWhich = 0;
//                    strorageTask();
//                }
//            }
//        }
    }

    /**
     * 退出应用
     */
    private void exitApp() {
        if (downloadTask != null) {
            downloadTask.cancel(true);
            downloadTask = null;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
                System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        },500);
    }
}
